<template>
	<div id="image-location">
		<div style="display: none;" class="imgs"><img v-for="item in srcs" :src="item.src" @load="getExif" /></div>
		<div id="input">
			<el-upload drag action="#" :show-file-list="false" :before-upload="beforeUpload">
				<i class="el-icon-upload"></i>
				<div class="el-upload__text">
					将文件拖到此处，或
					<em>点击上传</em>
				</div>
				<span @click.stop>
					<el-input
						v-model="tempSrc"
						@click.stop
						placeholder="图片URL或经纬度"
						@keyup.enter.native="
							parseInput(tempSrc);
							tempSrc = '';
						"
					></el-input>
					<el-tooltip class="item" effect="dark" placement="top">
						<i class="el-icon-question"></i>
						<div slot="content">
							<div>以http开头的视为图片</div>
							<div>包含°视为度分秒格式,会自动转化成小数,格式A°B'C,读作A度B分C秒</div>
							<div>百度坐标系(小数格式)前面需加上B标识,否则位置不准</div>
							<div>
								其他坐标系视为火星坐标系
								<a target="_blank" href="https://lbs.baidu.com/index.php?title=jspopularGL/guide/coorinfo" style="color: red;text-decoration: underline;">
									参考资料
								</a>
							</div>
							<div>有问题翻转经纬再试一次,输入完成回车会自动计算</div>
							<div>如果你看到定位在印度附近,你可能需要翻转你的经纬度</div>
						</div>
					</el-tooltip>
				</span>
			</el-upload>
			<div class="list">
				<el-table v-if="showTable" :data="srcs" style="width: 100%;">
					<el-table-column label="图片" width="60" align="center">
						<template slot-scope="scope">
							<el-image class="img" :src="scope.row.src" :preview-src-list="srcList"></el-image>
						</template>
					</el-table-column>
					<el-table-column label="定位" width="80" align="center">
						<template slot-scope="scope">
							<el-button v-if="typeof scope.row.x === 'number'" @click="track(scope.row)" size="mini">定位</el-button>
							<el-button v-else-if="scope.row.x === false">获取中</el-button>
							<el-button v-else type="text">无定位</el-button>
						</template>
					</el-table-column>
					<el-table-column label="百度经纬度" align="center">
						<template slot-scope="scope">
							<el-button v-if="typeof scope.row.x === 'number'" type="text" @click="copy(scope.row.x + ',' + scope.row.y)">
								{{ scope.row.x }},{{ scope.row.y }}
							</el-button>
						</template>
					</el-table-column>
				</el-table>
			</div>
		</div>
		<div id="map"></div>
	</div>
</template>

<script>
import EXIF from 'exif-js';
import { $post, $get, BASE_URL } from '@/puigins/request.js';
import loadImage from '@/utils/loadImage.js';
import copy from '@/utils/copy.js';

export default {
	name: 'imageLocation',
	mounted() {
		let map = new BMap.Map('map');
		map.centerAndZoom('北京', 11); // 初始化地图,设置城市和地图级别。
		map.enableScrollWheelZoom(true);
		this.map = map;
		// let x=this.point2float("112°54'59.253\"")
		// let y=this.point2float("24°7'27.827\"")
		// console.log(x+","+y)

		// let point = new BMap.Point(x, y);

		// //定位到当前位置
		// setTimeout(()=>{
		// 	map.centerAndZoom(point, 18);
		// },2000)

		// //添加标点
		// let marker = new BMap.Marker(point);
		// map.addOverlay(marker);
	},
	data() {
		return {
			location: true,
			srcs: [],
			tempSrc: '',
			showTable: true
		};
	},
	methods: {
		copy(s) {
			copy(s);
			this.$message.success('已复制');
		},
		beforeUpload(f) {
			let url = window.URL.createObjectURL(f);
			this.pushImage(url);
			return false;
		},
		getExif(e) {
			let img1 = e.path[0];
			let self = this;
			let src = img1.src;
			let item = self.srcs.find(item => item.src === src);
			EXIF.getData(img1, function() {
				let lat = EXIF.getTag(this, 'GPSLatitude');
				let lng = EXIF.getTag(this, 'GPSLongitude');
				if (!lat || !lng) {
					self.$message.warning('图片没有位置信息');
					console.log(lat, lng, img1);
					return;
				}
				self.srcs.forEach(item => {
					if (item.src === src) {
						item.x = item.y = false;
					}
				});

				lat = self.point2float(`${lat[0]}°${lat[1]}'${lat[2]}"`);
				lng = self.point2float(`${lng[0]}°${lng[1]}'${lng[2]}"`);
				self.location2baidu(lng, lat, src);
			});
		},
		location2baidu(lng, lat, src) {
			$get(`/util/apiProxy/baiduMapLocationGeoconvProxy`, {
				coords: `${lng},${lat}`
			}).then(res => {
				if (res.code == 200) {
					let data = JSON.parse(res.data);
					console.log(data);
					let result = data.result[0];
					let x = result.x;
					let y = result.y;

					//从srcs中找到图片，并设置x,y
					if (src) {
						this.srcs.forEach(item => {
							if (item.src === src) {
								item.x = x;
								item.y = y;
							}
						});
					}

					this.showTable = false;
					this.$nextTick(() => (this.showTable = true));

					this.location = true;
					let map = this.map;
					let point = new BMap.Point(x, y);

					//定位到当前位置
					map.centerAndZoom(point, 18);

					//添加标点
					let marker = new BMap.Marker(point);

					marker.addEventListener('click', function(e) {
						let opts;

						let content;
						if (isNaN(src)) {
							content = document.createElement('img');
							content.style.width = 200 + 'px';
							// content.style.height=200+'px'
							content.src = src;
							opts = {
								width: 200, // 信息窗口宽度
								height: 200 // 信息窗口高度info
							};
						} else {
							content = x + ',' + y;
							opts = {
								width: 350, // 信息窗口宽度
								height: 30 // 信息窗口高度info
							};
						}

						let infoWindow = new BMap.InfoWindow(content, opts); // 创建信息窗口对象

						// console.log(f)
						this.openInfoWindow(infoWindow);
					});

					map.addOverlay(marker);
				} else {
					this.$msgError(res);
				}
			});
		},
		track(item) {
			if (typeof item.x === 'number') {
				let point = new BMap.Point(item.x, item.y);

				this.map.centerAndZoom(point, 18);
			} else {
				console.log('无定位', item);
			}
		},
		point2float(point) {
			let du = parseFloat(point.substring(0, point.indexOf('°')).trim());
			let fen = parseFloat(point.substring(point.indexOf('°') + 1, point.indexOf("'")).trim());
			let miao = parseFloat(point.substring(point.indexOf("'") + 1).trim());
			let duStr = du + fen / 60 + miao / 60 / 60;
			return duStr.toString();
		},
		pushImage(url) {
			loadImage(url)
				.then(res => {
					this.srcs.push({
						src: res.src,
						x: null,
						y: null
					});
				})
				.catch(e => {
					loadImage(BASE_URL + '/img-proxy?url=' + url).then(res => {
						this.srcs.push({
							src: res.src,
							x: null,
							y: null
						});
					});
				});
		},
		parseInput(s) {
			if (s.startsWith('http')) {
				this.pushImage(s);
			} else if (s.indexOf('°') > -1 && s.indexOf(',') > -1) {
				//度分秒格式
				let arr = s.split(',');
				let y = this.point2float(`${arr[0]}`);
				let x = this.point2float(`${arr[1]}`);
				let src = new Date().getTime().toString();
				console.log(typeof x, y);
				this.srcs.push({
					src,
					x: null,
					y: null
				});
				this.location2baidu(x, y, src);
			} else if (s.indexOf(',') > -1) {
				if (s.indexOf('B') === 0) {
					//百度坐标系
					s = s.substring(1);
					let arr = s.split(',');

					let x = parseFloat(arr[0]);
					let y = parseFloat(arr[1]);
					let src = new Date().getTime().toString();
					console.log(arr);
					console.log(x, y);
					this.srcs.push({
						src,
						x,
						y
					});

					//百度坐标系
					let point = new BMap.Point(x, y);

					//定位到当前位置
					this.map.centerAndZoom(point, 18);

					//添加标点
					let marker = new BMap.Marker(point);
					marker.addEventListener('click', function(e) {
						let opts = {
							width: 350, // 信息窗口宽度
							height: 30 // 信息窗口高度info
						};

						let infoWindow = new BMap.InfoWindow(x + ',' + y, opts); // 创建信息窗口对象

						// console.log(f)
						this.openInfoWindow(infoWindow);
					});

					this.map.addOverlay(marker);
				} else {
					//其他坐标系
					let arr = s.split(',');
					let x = arr[0];
					let y = arr[1];
					let src = new Date().getTime().toString();
					this.srcs.push({
						src,
						x: null,
						y: null
					});
					this.location2baidu(x, y, src);
				}
			}
		}
	},
	computed: {
		srcList() {
			let arr = [];
			this.srcs.forEach(s => arr.push(s.src));
			return arr;
		}
	}
};
</script>

<style lang="scss">
#image-location {
	display: flex;
	position: absolute;
	width: 100%;
	height: 100%;
	flex-direction: row-reverse;
	#input {
		display: flex;
		flex-direction: column;
		align-items: center;
		justify-content: flex-start;

		flex: 1;
		.el-input {
			width: 220px;
		}
		.el-upload {
			margin-top: 20px;
		}
		.list {
			width: 80%;
			margin: 0 auto;
			.img {
				width: 40px;
				height: 40px;
			}
		}
	}
	#map {
		flex: 1;
	}
}
</style>
